class Promise {
	constructor(executor) {
		this.state = "pending";
		this.result = undefined;
		this.callback = [];
		const onResolved = function (v) {
			if (this.state !== "pending") return;
			this.state = "fulfilled";
			this.result = v;
			this.callback.forEach(item=>item.onResolved())
		}
		const onRejected = function (v) {
			if (this.state !== "pending") return;
			this.state = "rejected";
			this.result = v;
			this.callback.forEach(item=>item.onRejected())
		}
		try {
			executor(onResolved.bind(this), onRejected.bind(this));
		} catch (err) {
			onRejected.call(this, err);
		}
		
	}
	catch(onRejected){
		return this.then(undefined,onRejected);
	}
	then(onResolved, onRejected) {
		if(!(onResolved instanceof Function)){
			onResolved = value=>value;
		}
		if(!(onRejected instanceof Function)){
			onRejected = reason=>{
				throw reason;
			}
		}
		return new Promise(function (resolve,reject) {
			setTimeout(function () {
				const _common = function(callback){
					try{
						// 失败回调的返回值
						const v = callback(this.result);
						if(v instanceof Promise){
							v.then(resolve,reject)
						}else{
							resolve(v);
						}
					}catch (err){
						reject(err);
					}
				}
				if (this.state === "fulfilled") {
					_common.call(this,onResolved)
				} else if (this.state === "rejected") {
					_common.call(this,onRejected);
				}else{
					this.callback.push({
						onResolved:_common.bind(this,onResolved),
						onRejected:_common.bind(this,onRejected)
					});
				}
			}.bind(this))
		}.bind(this));
	}
}

export default Promise;